<!--
  * 拣货单
  *
-->
<template>
  <!---------- 查询表单form begin ----------->
  <a-card size="small" :bordered="false" :hoverable="false" class="query-form-wrapper smart-margin-bottom10 smart-radius-2">
    <a-form :model="queryForm" labelAlign="left">
      <a-row :gutter="[8, 10]">
        <a-col :span="{ sm: 7, md: 6 }">
          <a-form-item label="单据日期" class="smart-margin-bottom0">
            <custom-range-picker v-model:value="queryForm.create_time" />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="单据编号" class="smart-margin-bottom0">
            <a-input v-model:value.trim="queryForm.no" placeholder="请输入" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="源订单号" class="smart-margin-bottom0">
            <a-input v-model:value.trim="queryForm.source_order_no" placeholder="请输入" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="拣货状态" class="smart-margin-bottom0">
            <EnumSelect enum-name="PICKORDER_STATUS_ENUM" v-model:value="queryForm.status" placeholder="请选择" @submit="onSearch" />
          </a-form-item>
        </a-col>

        <a-col :span="4">
          <a-button-group>
            <a-button type="primary" html-type="submit" @click="onSearch">
              <template #icon>
                <SearchOutlined />
              </template>
              查询
            </a-button>
            <a-button @click="resetQuery">
              <template #icon>
                <ReloadOutlined />
              </template>
              重置
            </a-button>
          </a-button-group>
        </a-col>
      </a-row>
    </a-form>
  </a-card>
  <!---------- 查询表单form end ----------->

  <a-card size="small" :bordered="false" :hoverable="true" class="query-table-wrapper">
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block"> </div>
      <div class="smart-table-setting-block">
        <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.BUSINESS.ERP.GOODS" :refresh="queryData" />
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->
    <div class="table-wrapper">
      <a-table size="small" :dataSource="tableData" :columns="columns" rowKey="id" bordered :scroll="{ x: 'max-content', y: tableScrollY }" :pagination="false" :showSorterTooltip="false" :loading="tableLoading" :row-selection="{}">
        <template #bodyCell="{ text, record, column }">
          <template v-if="column.dataIndex === 'no'">
            <CopyText :text="text">
              <a @click="detail(record)">{{ text }}</a>
            </CopyText>
          </template>
          <template v-if="column.dataIndex === 'source_order_no'">
            <CopyText :text="text">
              <div class="two-line-ellipsis">
                {{ text }}
              </div>
            </CopyText>
          </template>
          <template v-if="Array.isArray(column.dataIndex) && column.dataIndex.join('.') === 'load.no'">
            <CopyText :text="text" />
          </template>
          <template v-if="column.dataIndex === 'status'">
            {{ getDescByValue('PICKORDER_STATUS_ENUM', text) }}
          </template>
          <template v-if="column.dataIndex === 'type'">
            {{ getDescByValue('PICKORDER_TYPE_ENUM', text) }}
          </template>
          <template v-if="column.dataIndex === 'delivery_method'">
            {{ getDescByValue('DELIVERY_METHOD_ENUM', text) }}
          </template>
          <template v-if="column.dataIndex === 'action'">
            <div class="smart-table-operate">
              <a-button @click="detail(record)" type="link" style="color: #97999c">详情</a-button>
              <a-button @click="print(record)" type="link">打印</a-button>
              <!-- <a-button @click="cancelPick(record)" danger type="link" v-privilege="'picking:cancel'" v-if="[PICKORDER_STATUS_ENUM.PENDING_PICK.value, PICKORDER_STATUS_ENUM.PICKING.value].includes(record.status) && getCompanyInfo.out_strategy === OUT_STRATEGY.SCHEDULE_PICK_LOAD.value">取消拣货</a-button> -->
            </div>
          </template>
        </template>
      </a-table>
    </div>

    <div class="smart-query-table-page query-table-page">
      <a-pagination showSizeChanger showQuickJumper show-less-items :pageSizeOptions="PAGE_SIZE_OPTIONS" :defaultPageSize="queryForm.limit" v-model:current="queryForm.page" v-model:pageSize="queryForm.limit" :total="total" @change="queryData" @showSizeChange="queryData" :show-total="(total) => `共${total}条`" />
    </div>
    <!---------- 详情 begin ----------->
    <PickingDetailsModal ref="detailRef" />
    <!---------- 详情 end ----------->
    <pickingPrintModal ref="printRef" />
  </a-card>
</template>
<script setup lang="ts">
import CustomRangePicker from '@/components/business/custom-range-picker/index.vue'
import pickingPrintModal from './components/picking-print-modal.vue'
import PickingDetailsModal from './components/picking-details-modal.vue'
import { message, Modal } from 'ant-design-vue'
import { pickOrderApi } from '@/api/business/storage/picking-api'
import { PAGE_SIZE_OPTIONS, TIME_RANGE_PRESETS } from '@/constants/system/common-const'
import { errorSentry } from '@/lib/error-sentry'
import TableOperator from '@/components/support/table-operator/index.vue'
import { TABLE_ID_CONST } from '@/constants/support/table-id-const'
import EnumSelect from '@/components/framework/enum-select/index.vue'
import _ from 'lodash'
import { useQuery } from '@/hooks/web/use-query-hook'
import { QUERY_FORM_OP } from '@/constants/support/query-form-op-const'
import { useEnums } from '@/hooks/plugins/useEnums'
import { useAppConfigStore } from '@/store/modules/app-store'
import { useResize } from '@/hooks/web/use-resize-hook'
import { PICKORDER_STATUS_ENUM } from '@/constants/business/storage/picking/picking-const'
import { OUT_STRATEGY } from '@/constants/business/storage/process-rules/process-rules-const'
import { useUserStore } from '@/store/modules/user-store'
const appConfigStore = useAppConfigStore()
const { getCompanyInfo } = useUserStore()
const { getDescByValue } = useEnums()

// ----------------------------- 计算表格高度 -----------------------------
const { tableScrollY } = useResize()

// ---------------------------- 表格列 ----------------------------

const columns = ref([
  {
    title: '单据编号',
    dataIndex: 'no',
    width: appConfigStore.$state.compactFlag ? 150 : 180
  },
  {
    title: '源订单号',
    dataIndex: 'source_order_no',
    width: (appConfigStore.$state.compactFlag ? 260 : 280) * 1.37
  },
  {
    title: '拣货类型',
    dataIndex: 'type'
  },
  {
    title: '拣货状态',
    dataIndex: 'status'
  },
  {
    title: '应拣数量',
    dataIndex: 'total_num'
  },
  {
    title: '拣货人',
    dataIndex: 'operator_name'
  },
  {
    title: '拣货完成时间',
    dataIndex: 'picked_at'
  },
  {
    title: '装车单号',
    dataIndex: ['load', 'no'],
    width: appConfigStore.$state.compactFlag ? 260 : 280
  },
  {
    title: '配送方式',
    dataIndex: 'delivery_method'
  },
  {
    title: '配送司机',
    dataIndex: ['load', 'driver', 'name']
  },
  {
    title: '创建时间',
    dataIndex: 'create_time'
  },
  {
    title: '订单备注',
    dataIndex: 'remark'
  },
  {
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
    width: 120
  }
])

// ---------------------------- 查询数据表单和方法 ----------------------------
const { queryForm, tableData, tableLoading, total, resetQuery, onSearch, queryData } = useQuery({
  fetchDataApi: async (params) => {
    const res = await pickOrderApi.queryList(params)
    return {
      list: res.data.data,
      total: res.data.total
    }
  },
  queryFormFilter: {
    create_time: TIME_RANGE_PRESETS[0].value,
    source_order_no: '',
    no: '',
    status: undefined
  },
  queryFormOp: {
    create_time: QUERY_FORM_OP['范围查询'],
    source_order_no: QUERY_FORM_OP['模糊查询'],
    no: QUERY_FORM_OP['模糊查询'],
    status: QUERY_FORM_OP['全等查询']
  }
})
const route = useRoute()
onMounted(() => {
  if (route.query.no) {
    queryForm.value.no = route.query.no
    queryForm.value.create_time = []
  }
  queryData()
})

// ---------------------------- 详情 ----------------------------
const detailRef = ref()

const detail = (goodsData) => {
  detailRef.value.showDrawer(goodsData)
}
// 打印
const printRef = ref()
function print(goodsData) {
  printRef.value.showDrawer(goodsData)
}
// ---------------------------- 取消拣货 ----------------------------
function cancelPick(record) {
  Modal.confirm({
    title: '确认取消拣货单？',
    onOk: async () => {
      try {
        const res = await pickOrderApi.cancel({ id: record.id })
        message.success(res.msg)
        onSearch()
      } catch (error) {
        message.error(error.msg)
      } finally {
        return Promise.resolve()
      }
    }
  })
}
</script>
<style scoped>
/* 两行文本省略 */
.two-line-ellipsis {
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2; /* 限制两行 */
  -webkit-box-orient: vertical;
  text-overflow: ellipsis;
  white-space: normal; /* 允许换行 */
}
</style>
